<?php

class CompanyController extends Controller {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'ext.starship.RestfullYii.filters.ERestFilter +
                REST.GET, REST.PUT, REST.POST, REST.DELETE'
            ),
        );
    }

    public function actions() {
        return array(
            'REST.' => 'ext.starship.RestfullYii.actions.ERestActionProvider',
        );
    }

    public function accessRules() {
        return array(
            array('allow', 'actions' => array('REST.GET', 'REST.PUT', 'REST.POST', 'REST.DELETE'),
                'users' => array('*'),
            ),

        );
    }

    public function actionIndex() {
        $this->layout = 'null';
        if (!isset($_GET['id'])) throw new CHttpException(999, 'Invalid request');
        $company = Company::model()->findByPk($_GET['id']);
        if ($company == null) throw new CHttpException(999, 'Invalid request');

        $criteria = new CDbCriteria();
        $criteria->select = ('id');
        $criteria->condition = 'published = 1 and company_id = :id';
        $criteria->params = array(':id' => $company->id);

        $total = Comment::model()->count($criteria);
        $comments = Comment::model()->findAll(array(
            'select' => 'id,username,created_time,content,like_count',
            'condition' => 'company_id = :id AND published = 1 and parent_id = 0',
            'limit' => 2,
            'offset' => 0,
            'order' => 'id DESC',
            'params' => array('id' => $company->id)
        ));
        $results = array();
        foreach ($comments as $comment) {

            array_push($results, array(
                'id' => $comment->id,
                'username' => $comment->username,
                'created_time' => HSCommon::calculateTime($comment->created_time),
                'content' => $comment->content,
            ));
        }

        $readMore = 2 < $total;

        $this->render('index', array('model' => $company, 'comments' => $results, 'readMore' => $readMore));
    }

    public function actionCreate() {
        $detect = new Mobile_Detect;
        if ($detect->isMobile()) {
            $this->layout = '//layouts/main_mobile';
        }
        $model = new Company;
        Yii::app()->language = 'vi';

        if (isset($_POST['Company'])) {
            $model->attributes = $_POST['Company'];

            $file = CUploadedFile::getInstance($model, 'picture');
            $year = date('Y');
            $month = date('m');
            $day = date('d');

            $mess = "<h2>Có đăng ký công ty mới ở " . Yii::app()->params['site_name'] . "</h2>
                      <p>Tên công ty: $model->name </p>
                      <p>Tên chủ sở hữu: $model->owner </p>
                      <p>Địa chỉ:  $model->address </p>
                      <p>Thành phố: $model->city </p>
                      <p>Số điện thoại: $model->phone </p>
                    ";

            $model->validate();
            if (count($model->getErrors()) > 0) {
                return $this->render('create', array(
                    'model' => $model,
                    'categories' => Category::model()->findAll()
                ));
            }

            if ($file != null) {
                $extension = $file->getExtensionName();
                $fileName = HSCommon::getSEO($model->name) . '_' . rand(10000, 99999) . '.' . $extension;

                $base = HSCommon::checkFolderExisted($year, $month, $day, 'company');

                if ($file->saveAs($base . "/$year/$month/$day/$fileName")) {
                    $model->picture = "/pictures/company/$year/$month/$day/$fileName";

                    if ($model->save()) {
                        $mess .= "<p>ID: $model->id</p>";
//                        Mailer::sendEmail(Yii::app()->params['admin_email'], 'Đăng ký công ty mới', $mess);
                        Yii::app()->user->setFlash('success', "Đã đăng ký thành công, vui lòng chờ kiểm duyệt.");
                        $this->redirect(HSUrl::getMapUrl());
                    }
                } else {
                    $model->addError('picture', 'Không lưu được ảnh');
                }

            } else {

                $model->picture = "/pictures/no-image.png";
                if ($model->save()) {
                    $mess .= "<p>ID: $model->id</p>";
//                    Mailer::sendEmail(Yii::app()->params['admin_email'], 'Đăng ký công ty mới', $mess);

                    Yii::app()->user->setFlash('success', "Đã đăng ký thành công, vui lòng chờ kiểm duyệt.");
                    $this->redirect(HSUrl::getMapUrl());
                }

            }
        }

        $this->render('create', array(
            'model' => $model,
            'categories' => Category::model()->findAll()
        ));
    }

    #region API
    public function restEvents() {
        $this->onRest('req.get.getLatest.render', function () {
            $criteria = new CDbCriteria();
            $criteria->condition = 'published = 1';
            $criteria->order = 'id desc';
            $criteria->limit = 10;
            $this->renderJSON(array(
                'type' => 'rest',
                'data' => Company::model()->findAll($criteria),
                'modelName' => 'Company',
            ));
        });
    }

    #endregion
}